from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from .models import UserProfile, UserActivity, UserPreference


class UserProfileInline(admin.StackedInline):
    """用户资料内联编辑"""
    model = UserProfile
    can_delete = False
    verbose_name = '用户资料'
    verbose_name_plural = '用户资料'
    
    fieldsets = (
        ('个人信息', {
            'fields': ('avatar', 'phone', 'address')
        }),
        ('偏好设置', {
            'fields': ('theme', 'language', 'timezone'),
            'classes': ('collapse',)
        }),
        ('通知设置', {
            'fields': ('email_notifications', 'push_notifications', 'sms_notifications'),
            'classes': ('collapse',)
        }),
    )


class UserAdmin(BaseUserAdmin):
    """扩展用户管理"""
    inlines = (UserProfileInline,)
    
    def get_inline_instances(self, request, obj=None):
        """确保用户资料存在"""
        if obj:
            UserProfile.objects.get_or_create(user=obj)
        return super().get_inline_instances(request, obj)


# 重新注册User模型
admin.site.unregister(User)
admin.site.register(User, UserAdmin)


@admin.register(UserActivity)
class UserActivityAdmin(admin.ModelAdmin):
    """用户活动记录管理"""
    list_display = ['user', 'activity_type', 'description', 'ip_address', 'created_at']
    list_filter = ['activity_type', 'created_at']
    search_fields = ['user__username', 'description', 'ip_address']
    ordering = ['-created_at']
    
    fieldsets = (
        ('活动信息', {
            'fields': ('user', 'activity_type', 'description')
        }),
        ('详细数据', {
            'fields': ('activity_data',),
            'classes': ('collapse',)
        }),
        ('请求信息', {
            'fields': ('ip_address', 'user_agent'),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at',),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['created_at']
    
    def has_add_permission(self, request):
        """禁止手动添加活动记录"""
        return False
    
    def has_change_permission(self, request, obj=None):
        """禁止修改活动记录"""
        return False


@admin.register(UserPreference)
class UserPreferenceAdmin(admin.ModelAdmin):
    """用户偏好设置管理"""
    list_display = ['user', 'key', 'value_type', 'created_at']
    list_filter = ['value_type', 'created_at']
    search_fields = ['user__username', 'key']
    ordering = ['user', 'key']
    
    fieldsets = (
        ('偏好信息', {
            'fields': ('user', 'key', 'value_type')
        }),
        ('值设置', {
            'fields': ('string_value', 'integer_value', 'float_value', 'boolean_value', 'json_value')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at'),
            'classes': ('collapse',)
        }),
    )
    readonly_fields = ['created_at', 'updated_at']
    
    def get_form(self, request, obj=None, **kwargs):
        """根据值类型显示对应字段"""
        form = super().get_form(request, obj, **kwargs)
        if obj:
            # 根据值类型隐藏其他值字段
            value_fields = ['string_value', 'integer_value', 'float_value', 'boolean_value', 'json_value']
            for field in value_fields:
                if field != f"{obj.value_type}_value":
                    if field in form.base_fields:
                        form.base_fields[field].widget.attrs['style'] = 'display:none;'
        return form
